package com.yy.service.impl;

import com.yy.mapper.ArticleMapper;
import com.yy.mapper.CollectionMapper;
import com.yy.pojo.Article;
import com.yy.pojo.Collection;
import com.yy.pojo.bo.CollectionBo;
import com.yy.pojo.vo.ArticleVo;
import com.yy.service.CollectionService;
import com.yy.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CollectionServiceImpl implements CollectionService {
    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public String add(CollectionBo bo) {
        //获取当前登录用户id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        //根据用户id和文章id查询
        Collection collection = collectionMapper.selectByUserIdAndArticleId(userId,bo.getArticleId());
        if (collection!=null){
            Integer i = collectionMapper.deleteById(collection.getCollectionId());
            if (i>0){
                return "取消收藏";
            }
        }else {
            Integer insert = collectionMapper.insert(userId, bo.getArticleId());
            if (insert>0){
                return "收藏成功";
            }
        }
        return "";
    }

    @Override
    public List<ArticleVo> list() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Collection> collection = collectionMapper.selectByUserId(userId);
        List<ArticleVo> articleVos = new ArrayList<>();
        if (collection!=null){
            collection.forEach(item->{
                ArticleVo article = articleMapper.selectById(item.getArticleId());
                articleVos.add(article);
            });
        }
        return articleVos;
    }
}
